package com.socialbank.web.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.nybank.fastdfs.FastDFSFile;
import com.nybank.fastdfs.FileManager;
import com.socialbank.web.util.Base64Util;
import com.socialbank.web.util.JsonUtil;

@Controller
public class Upload extends BaseController{

	@RequestMapping(method=RequestMethod.POST,value="/upload")
	public void upload(HttpServletRequest request, HttpServletResponse response,@RequestBody String imgstr){
		String fileType = Base64Util.getImgType(imgstr);
		byte[] file_buff = Base64Util.GenerateImage(Base64Util.getBase64Content(imgstr));
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		//以时间命名
		FastDFSFile dfsFile = new FastDFSFile(sdf.format(new Date()).toString(), file_buff, fileType);
		Map<String, Object> map = FileManager.upload(dfsFile);
		print(response, JsonUtil.mapToJsonString(map));
	}
	
	@RequestMapping(method=RequestMethod.DELETE,value="/upload")
	public void delete(HttpServletRequest request, HttpServletResponse response,@RequestBody Map<String, String> fastDfs){
		Map<String, Object> map = new HashMap<>();
		try {
			FileManager.deleteFile(fastDfs.get("groupName"), fastDfs.get("remoteFileName"));
			map.put("content", "删除成功");
		} catch (Exception e) {
			map.put("content", "删除失败");
		}
		print(response, JsonUtil.mapToJsonString(map));
	}
}